<template>
  <div style="padding: 15px;">
    <vxe-toolbar id="userLoginId" :setting="{storage: true}" export :refresh="{query: findList}">
      <template v-slot:buttons>
        <el-button @click="findList">查询</el-button>
        <el-button @click="funcAddEdit('add')">新增</el-button>
        <el-button @click="start">启用</el-button>
        <el-button @click="block">停用</el-button>
      </template>
    </vxe-toolbar>
    <vxe-table
      ref="xTable"
      border
      resizable
      stripe
      highlight-current-row
      highlight-hover-row
      row-id="id"
      height="700"
      :align="allAlign"
      :loading="loading"
      :data="tableData"
      remote-sort
      @sort-change="sortList"
      :seq-config="{startIndex: listQuery.pageNum * listQuery.pageSize - listQuery.pageSize}"
    >
      <vxe-table-column type="seq" width="60"></vxe-table-column>
      <vxe-table-column type="checkbox" width="60"></vxe-table-column>


      <vxe-table-column>
        <vxe-table-column field="status" title="状态" min-width="90" sortable show-header-overflow show-overflow/>
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.status" placeholder="请选择状态" clearable>
            <el-option value="0" label="启用"/>
            <el-option value="1" label="停用"/>
          </el-select>
        </template>
      </vxe-table-column>


      <vxe-table-column>
        <vxe-table-column field="phone" title="登录账号" min-width="120" sortable />
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.phone" placeholder="请输入登录账号" maxlength="100" clearable />
        </template>
      </vxe-table-column>


      <vxe-table-column min-width="100">
        <vxe-table-column field="name" title="姓名" min-width="100" sortable />
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.name" placeholder="请输入姓名" maxlength="64" clearable />
        </template>
      </vxe-table-column>


      <vxe-table-column>
        <vxe-table-column field="partyType" title="账号类型" min-width="100" sortable show-header-overflow show-overflow/>
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.partyType" placeholder="请选择账号类型" clearable>
            <el-option value="GROUP_ADMIN" label="管理员"/>
            <el-option value="USER" label="操作员"/>
          </el-select>
        </template>
      </vxe-table-column>

      <vxe-table-column min-width="100">
        <vxe-table-column field="shipmentName" title="入驻商权限" min-width="200" sortable />
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.shipmentName" placeholder="请选择" clearable />
        </template>
      </vxe-table-column>

            <vxe-table-column min-width="100">
        <vxe-table-column field="warehouseName" title="仓库权限" min-width="200" sortable />
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.warehouseName" placeholder="请选择" clearable />
        </template>
      </vxe-table-column>


      <vxe-table-column>
        <vxe-table-column field="gmtCreated" title="创建时间"  min-width="250"  sortable />
        <template v-slot:header="{ column }">
          <div class="block">
            <el-date-picker
              v-model="gmtCreatedRange"
              type="daterange"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptions"
              style="width:100%"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="right"
              @change="changeDate"
            />
          </div>
        </template>
      </vxe-table-column>
      <vxe-table-column title="操作" fixed="right" min-width="60">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="编辑" placement="top">
            <vxe-button type="text" @click="funcAddEdit('edit',scope.row.phone)">
              <i class="el-icon-edit" />
            </vxe-button>
          </el-tooltip>
          <el-tooltip class="item" content="授权" placement="top" v-if="scope.row.showAuthorizationMenu === 1">
            <vxe-button type="text" icon="el-icon-setting" @click="authorize(scope.row.phone)" />
          </el-tooltip>
        </template>
      </vxe-table-column>
    </vxe-table>
    <vxe-pager
      :loading="loading"
      :current-page.sync="listQuery.pageNum"
      :page-size.sync="listQuery.pageSize"
      :total="listQuery.total"
      :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
      @page-change="handlePageChange"
    />

    <vxe-modal v-model="modelAddFlag" :title="operationTitle" width="550" destroy-on-close resize>
      <compAddEdit :operation-type="operationType" :operation-code="operationCode"  @fatherAddMethod="funcAddEdit();findList()" />
    </vxe-modal>
    <vxe-modal v-model="modelDetailFlag" title="详情" width="550" height="700" resize>
      <compDetail ref="detailRef" />
    </vxe-modal>
    <vxe-modal
      v-model="modelAuthorize"
      title="账号授权"
      width="500"
      height="650"
      resize
      :loading="authorizeLoad"
      destroy-on-close
    >
      <accountAuth :operation-code="phone" @operationComplete="authorize" />
    </vxe-modal>
  </div>
</template>
<script>
import Vue from 'vue'
import 'xe-utils'
import VXETable from 'vxe-table'
import 'vxe-table/lib/index.css'
import XEUtils from 'xe-utils'
import VXEUtils from 'vxe-utils'
Vue.use(VXETable, VXEUtils, XEUtils, { mounts: ['cookie'] })
import compAddEdit from './components/userLoginAdd.vue'
import compEdit from './components/userLoginEdit.vue'
import compDetail from './components/userLoginDetail.vue'
import accountAuth from './components/accountAuth.vue'
import request from '@/utils/request'
import groupSelect from "./components/groupSelect";
import {userActive, userUnActive} from '@/api/basicInfo'
export default {
  name: '账号管理',
  components: {
    compAddEdit,
    compEdit,
    compDetail,
    accountAuth,
    groupSelect
  },
  data() {
    return {
      phone:'',
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      allAlign:'center',
      operationType: '', //操作类型
      operationTitle: '', //操作类型标题
      operationCode: '', // 修改、详情，数据的id
      operation: {
        add: '添加',
        edit: '编辑',
        title: '添加',
        type: 'add',
      },
      message: '',
      loading: false,
      cascadeData:[],
      mloading: true, // 编辑数据加载框
      userLoginId: '', // 编辑数据需要的参数
      tableData: [],
      modelAddFlag: false,
      modelEditFlag: false,
      modelDetailFlag: false,
      copy: false,
      gmtCreatedRange: [],
      listQuery: {
        partyType: '',
        name: '',
        phone: '',
        shipmentCode:'',
        warehouseCode:'',
        gmtCreatedStart: '',
        gmtCreatedEnd: '',
        groupCode: '',
        pageNum: 1,
        pageSize: 10,
        sortField: '',
        sortType: '',
        total: 0
      },
      authorizeLoad: true, // 授权弹窗加载动画
      modelAuthorize: false, // 授权遮罩开关
    }
  },
  created() {
    this.findList();
  },
  methods: {
       //启用
      start() {
        let selectRecords = this.$refs.xTable.getCheckboxRecords()
        let arr = []
        selectRecords.forEach(i => {
          arr.push(i.phone)
        })
        arr = arr.join(",");
        if (arr.length != 0) {
          this.$confirm('确认启用吗？').then(_ => {
            this.loading = true
            userActive(arr).then(response => {
              this.$message({message: response.msg, type: 'success'})
              this.findList()
              this.loading = false
            })
          })
        } else {
          this.$message('没有能启用的数据！')
        }

      },
        //停用
      block() {
        let selectRecords = this.$refs.xTable.getCheckboxRecords()
        let arr = []
        selectRecords.forEach(i => {
          arr.push(i.phone)
        })
        arr = arr.join(",");
        if (arr.length != 0) {
          this.$confirm('确认停用吗？').then(_ => {
            this.loading = true
            userUnActive(arr).then(response => {
              this.$message({ dangerouslyUseHTMLString: true,message: response.msg, type: 'success'})
              this.findList()
              this.loading = false
            })
          }).catch(_ => {
          })
        } else {
          this.$message('没有能停用的数据！')
        }
      },
    findList() {
      this.loading = true
      return new Promise(resolve => {
        request({
          url: '/arpa-basic-api/users',
          method: 'get',
          params: this.listQuery
        }).then(response => {
          this.tableData = response.data.records
          this.listQuery.total = response.data.total
        }).then(_ =>{
          this.loading = false
          resolve();
        });
      });
    },
    // 排序
    sortList({ column, property, order }) {
      if (order) {
        this.listQuery.sortField = property
        this.listQuery.sortType = order
      } else {
        this.listQuery.sortField = ''
      }
      this.findList()
    },
    // 添加（修改）
    funcAddEdit(type, code) {
      this.modelAddFlag = !this.modelAddFlag
      if (type) {
        this.operationType = type
        this.operationTitle = this.operation[type]
      }
      if (code) {
        this.operationCode = code
      }
    },
    // 详情方法
    funcDetail(phone) {
      this.$refs.detailRef.getInfo(phone)
      this.modelDetailFlag = true
    },
    // 账号授权
    authorize(phone) {
      if (phone) this.phone = phone
      this.modelAuthorize = !this.modelAuthorize
      this.authorizeLoad = this.modelAuthorize
    },
    changeDate(value) {
      if(value){
        this.listQuery.gmtCreatedStart = value[0] + ' 00:00:00'
        this.listQuery.gmtCreatedEnd = value[1] + ' 23:59:59'
      }else{
        this.listQuery.gmtCreatedStart = ''
        this.listQuery.gmtCreatedEnd = ''
      }
    },
    changeStartDate(value) {
      this.listQuery.gmtCreatedStart = value + ' 00:00:00'
    },
    changeEndDate(value) {
      this.listQuery.gmtCreatedEnd = value + ' 23:59:59'
    },
    // 公共取消
    fatherCancel(modelFlag) {
      switch (modelFlag) {
        case 'add':
          this.modelAddFlag = false
          break
        case 'edit':
          this.modelEditFlag = false
          break
        case 'detail':
          this.modelDetailFlag = false
          break
        default:
      }
    },
    // 分页handle
    handlePageChange({ currentPage, pageSize }) {
      this.listQuery.pageNum = currentPage
      this.listQuery.pageSize = pageSize
      this.findList()
    },

  }
}
</script>

<style>
.vxe-table .vxe-body--column:not(.col--ellipsis), .vxe-table .vxe-footer--column:not(.col--ellipsis), .vxe-table .vxe-header--column:not(.col--ellipsis) {
 padding: 6px 0;
}
.vxe-toolbar{padding:0 0 10px 0}
</style>
